package cn.minimelon.api.config.handle;

import cn.hutool.core.util.ObjUtil;
import cn.minimelon.api.constant.HttpStatus;
import cn.minimelon.api.domain.common.AjaxResult;
import cn.minimelon.api.exception.BaseException;
import cn.minimelon.api.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;

import java.sql.SQLException;

/**
 * 全局异常处理
 */
@Slf4j
@Component
public class GlobalExceptionHandle implements Filter {

    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        try {
            chain.doFilter(ctx);
        } catch (ServiceException ex){
            Integer code = ex.getCode();
            AjaxResult aj = ObjUtil.isNotNull(code) ? AjaxResult.error(code, ex.getMessage()) : AjaxResult.error(ex.getMessage());
            ctx.render(aj);
        } catch (BaseException ee){
            log.error("模块：{} 编码：{} 内容：{}", ee.getModule(), ee.getCode(), ee.getMessage());
            AjaxResult aj = AjaxResult.error(HttpStatus.ERROR, ee.getMessage());
            ctx.render(aj);
        } catch (SQLException ee){
            AjaxResult aj = AjaxResult.error(HttpStatus.ERROR, String.format("数据库异常：%s", ee.getErrorCode()));
            ctx.render(aj);
        } catch (Throwable ex) {
            String requestURI = ctx.uri().getPath();
            log.error("请求地址'{}',失败'{}'", requestURI, ex.getMessage());
            AjaxResult aj = AjaxResult.error(HttpStatus.ERROR, ex.getMessage());
            ctx.render(aj);
        }
    }
}
